<?php

namespace App\Listeners;

use Dingo\Api\Event\ResponseWasMorphed;

class AddSuccessToResponse
{
    /**
     * 监听200状态下的响应,重组数据提供给前端调用
     * @param ResponseWasMorphed $event
     */
    public function handle(ResponseWasMorphed $event)
    {
        if($event->response->getStatusCode() == 200){
            $newResponse = [
                'message' => $event->content['message'] ?? 'OK!',
                'errcode' => $event->response->getStatusCode(),
                'data' => $event->content
            ];
            $event->content = $newResponse;
        }elseif($event->response->getStatusCode() == 422){
            $errorMessage = '';
            $errors = isset($event->content['errors']) ? $event->content['errors']->toArray() : [];
            foreach ($errors as $error){
                foreach ($error as $message){
                    $errorMessage .= $message . '<br/>';
                }
            }
            $event->content['message'] = $errorMessage ? : $event->content['message'];
        }elseif ($event->response->getStatusCode() == 500 && in_array(env('APP_ENV'), ['test', 'prod'])){
            $event->content['message'] = '哎呦~ 服务器崩溃了';
        }
    }
}
